/**
* File Name: pthrd_end1.c
* Auther: Jichang
* Environment: Fedora 7 server
* about the method of end thread.
*/
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<pthread.h>

/* way 1 */
void *tfn1(void *arg)
{
	printf("thread 1 retuning.\n");
	return (void*)111;  // same as exit(111) but don't recomend.
}
/* way 2 */
void *tfn2(void *arg)
{
	printf("thread 2 exiting.\n");
	pthread_exit((void*)222);
}
/* way 3 */
void *tfn3(void *arg)
{
	while(1) {
		//printf("thread 3: going to die in 3 seconds...\n");
		//sleep(1);

		 pthread_testcancel(); // You can add cancel-point to quit. 
	}
	return (void*)333;
}

int main(int argc, char *argv[])
{
	pthread_t tid;
	void *tret = NULL;
	
	/* way 1 */
	pthread_create(&tid, NULL, tfn1, NULL);
	pthread_join(tid, &tret);
	printf("thread 1 exit code: %ld\n\n", (unsigned long)tret);
	/* way 2 */
	pthread_create(&tid, NULL, tfn2, NULL);
	pthread_join(tid, &tret);
	printf("thread 2 exit code: %ld\n\n", (unsigned long)tret);
	/* way 3 */
	pthread_create(&tid, NULL, tfn3, NULL);
	sleep(3);
	pthread_cancel(tid);// result with -1 .
	pthread_join(tid, &tret);
	printf("thread 3 exit code: %ld\n\n", (unsigned long)tret);


	return 0;
}

